<?php

class SocialAccount extends AppModel
{
	var $name = "SocialAccount";
	protected $entityKey = 'user_id';
	protected $apiStatusMethod = 'postStatus';
	protected $apiName = null;
	protected $api;
	/**
	 * Get new Api
	 */
	function getApi($new = false)
	{
		if(!is_object($this->api) || $new == true)
		{
			$apiName = $this->apiName;
			$api = null;
			if($apiName == null)
			{
				$className = get_class($this);
				$accountName = substr($className,0,(strlen($className) - 7 ));
				$apiName = 'Sociable.'.$accountName.'Api';
			}
			App::import('Vendor',$apiName);
			$apiClass = array_pop(explode('.',$apiName));
			if(class_exists($apiClass))
			{
				$this->api = new $apiClass();
			}else
			{
				trigger_error("No Api Class for ".get_class($this).' was found',E_USER_WARNING);
			}
		}
		return $this->api;
	}
	
	/**
	* return whether has has linked its account or not
	* @param $entityId
	*/
	function hasAccount($entityId)
	{
		return $this->hasAny(array($this->entityKey=>$entityId));
	}
	
	/**
	 * 
	 * @param $entityId
	 * @param $message
	 */
	function postStatus($entityId,$message)
	{
		$return = false;
		if($this->hasAccount($entityId))
		{
			$accountInfo = $this->find('first',array('conditions'=>array($this->entityKey => $entityId)));
			$callback = $this->beforeApiStatusUpdate($accountInfo[$this->alias],$message);
			if(is_bool($callback) === false)
			{
				$message = $callback;
			}
			$return = $this->callApi($this->apiStatusMethod,$accountInfo[$this->alias],$message);
		}
		return $return;
	}
	
	function callApi($method,$parameters = array())
	{
		$miniumParameter = 2;
		if(func_num_args() > $miniumParameter)
		{
			$args = func_get_args();
			$parameters	= $args;
			array_shift($parameters);
		}
		$return = call_user_func_array(array($this->getApi(),$method,),$parameters);
		return $return;
	}
	
	function unlinkAccount($entityId)
	{
		if($entityId)
		{
			$this->deleteAll(array($this->entityKey=>$entityId));
		}
		return true;
	}
	/**
	 * Call beofre posting on social account
	 * return true / false or modified $message.
	 * @param $accontInfo
	 * @param $message
	 */
	function beforeApiStatusUpdate($accontInfo,$message = null)
	{
		$return = true;
		if(is_null($message) === false)
		{
			$return  = $message;
		}
		return $return;
	}
	
}
?>